﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using JWT;

namespace MiniPc.API
{
    public class JwtService : IJwtService
    {
        /// <summary>
        /// 注入JWTPptions
        /// </summary>
        private readonly JWTPptions _pptions;

        public JwtService(JWTPptions pptions)
        {
            _pptions = pptions;
        }

        //创建jwt的字符串
        public string CreateJwtStr(Claim[] claims)
        {
            //创建JWT字符串
            var token = new JwtSecurityToken(
                issuer: _pptions.Issuer,
                audience: _pptions.Audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: new SigningCredentials(
                    new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_pptions.SecretKey)),
                   SecurityAlgorithms.HmacSha256
                  )
                );

            string strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }


        /// <summary>
        /// 解密token
        /// </summary>
        /// <param name="Token"></param>
        /// <returns></returns>
        public bool GetClaimFtomToken(string Token,out Dictionary<string, string> keyValuePairs)
        {
            //以.号分割Token
            string[] Jwtparte = Token.Split('.');

            if (Jwtparte.Length<3)
            {
                keyValuePairs = null;
                return false;
            }

            //解析头部,并且反序列化
            string headerJson = Base64UrlEncoder.Decode(Jwtparte[0]);
            var header = JsonConvert.DeserializeObject<Dictionary<string, string>>(headerJson);


            //解析荷载,并且反序列化
            string PayJson = Base64UrlEncoder.Decode(Jwtparte[1]);
            var Pay = JsonConvert.DeserializeObject<Dictionary<string, string>>(PayJson);

            //签名无法解析，生成秘钥  进行比较
            var hs256 = new HMACSHA256(Encoding.UTF8.GetBytes(_pptions.SecretKey));

            string signHash = Base64UrlEncoder.Encode(hs256.ComputeHash(Encoding.UTF8.GetBytes(Jwtparte[0] + "." + Jwtparte[1])));

            if (!signHash.Equals(Jwtparte[2]))
            {
                keyValuePairs = null;
                return false;
            }
            //解析时间
            //DateTime StadateTime = Convert.ToDateTime(Pay["nbf"]);
            //DateTime EnddateTime = Convert.ToDateTime(Pay["exp"]);
            //if (DateTime.Now>StadateTime && DateTime.Now > EnddateTime)
            //{
            //    keyValuePairs = null;
            //    return false;
            //}

            keyValuePairs = Pay;
            return true;
        }
    }
}
